<template>
  <div>
    <el-dialog :append-to-body="true" :visible.sync="dialogVisible" width="940px">
      <div>
        <div v-loading="loading">
          <div class="form-seach">
            <el-form ref="form" :model="BindForm" label-width="80px" label-position="left">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="商品名称:" prop="commodityName" class="form-item">
                    <el-input v-model="BindForm.commodityName" placeholder="请输入商品名称" maxlength="30" class="cus-input" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商品分类:" prop="type" class="form-item">
                    <select-all-goods-category v-model="BindForm.type" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商品类型:" prop="goodsType" class="form-item">
                    <el-select v-model="BindForm.goodsType" :disabled="isParts" clearable filterable placeholder="请选择商品类型" style="width: 100%">
                      <el-option value="lease" label="租赁" />
                      <el-option value="sale" label="售卖" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item class="form-item">
                <el-button type="primary" @click="search">筛选</el-button>
                <el-button @click="resetForm">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div v-if="dialogVisible" class="ele-table">
            <el-table ref="goodsTable" :data="BindTable" highlight-current-row border max-height="280" :empty-text="loading ? '数据加载中' : (isSearch ? '未找到相关的商品' : '暂无商品')" @selection-change="handleSelectionChange">
              <!--              <el-table-column-->
              <!--                label="序号"-->
              <!--                type="index"-->
              <!--                align="center"-->
              <!--                width="80"-->
              <!--                :resizable="false"-->
              <!--                fixed="left"-->
              <!--              />-->
              <el-table-column
                type="selection"
                align="center"
                width="50"
              />
              <el-table-column label="商品主图" align="center" :resizable="false" width="80">
                <template slot-scope="scope">
                  <TableColumnGoodsImage :src="scope.row.img" />
                </template>
              </el-table-column>
              <el-table-column
                label="商品名称"
                prop="name"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="商品类型"
                prop="type"
                align="center"
                width="90"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.type == 'lease'" type="success" size="small">租赁</el-tag>
                  <el-tag v-else-if="scope.row.type == 'sale'" type="primary" size="small">售卖</el-tag>
                  <el-tag v-else type="info" size="small">未知</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="店铺"
                prop="busiName"
                align="center"
                :resizable="false"
              />
              <el-table-column
                label="商品状态"
                prop="state"
                align="center"
                width="90"
                :resizable="false"
              >
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.state == 0" type="info" size="small">未销售</el-tag>
                  <el-tag v-else-if="scope.row.state == 1" type="success" size="small">销售中</el-tag>
                  <el-tag v-else type="info" size="small">未知</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="pagination">
            <div>
              <div>
                <div style="display: inline-flex;">
                  <el-button plain size="small" @click="allSelection">全选</el-button>
                  <el-button plain size="small" @click="selectAddCommodity">添加</el-button>
                </div>
              </div>
            </div>
            <el-pagination
              background
              :page-sizes="[10, 20, 30, 50, 100]"
              :page-size="limit"
              :pager-count="5"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="pageSizeChange"
              @current-change="currentPageChange"
            />
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SelectAllGoodsCategory from '../SelectAllGoodsCategory/index'
import TableColumnGoodsImage from '../TableColumnGoodsImage/index'
import { getAllCommodity } from '@/api/customAPI/shop/homeSetting'

export default {
  name: 'SelectGoodsDialog',
  components: { TableColumnGoodsImage, SelectAllGoodsCategory },
  props: {
    title: {
      type: String,
      default: '请选择商品'
    },
    sku: {
      type: Boolean,
      default: false
    },
    onlyOnline: {
      type: Boolean,
      default: false
    },
    goodsType: {
      type: String,
      default: ''
    },
    goodsState: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      dialogVisible: false,
      page: 1,
      limit: 10,
      total: 0,
      isParts: false,
      loading: false,
      isSearch: false,
      BindForm: {
        commodityName: null,
        type: null,
        goodsType: null
      },
      BindTable: [],
      tempGoods: null,
      selectList: [],
      formData: null
    }
  },
  mounted() {
    if (this.goodsType === 'sale' && this.goodsState === 1) {
      this.BindForm.commdityState = '1'
      this.BindForm.goodsType = 'sale'
      this.isParts = true
    } else if (this.goodsType === 'lease' && this.goodsState === 1) {
      this.BindForm.commdityState = '1'
      this.BindForm.goodsType = 'lease'
      this.isParts = true
    }
    if (this.onlyOnline) {
      this.BindForm.commdityState = '1'
    }
  },
  /* watch: {
    'goodsType': {
      handler(newValue,oldValue) {
        if (this.goodsType === 'sale' && this.goodsState === 1) {
          this.BindForm.commdityState = '1'
          this.BindForm.goodsType = 'sale'
          this.isParts = true
        } else if (this.goodsType === 'lease' && this.goodsState === 1) {

        }
      }
    }
  },*/
  methods: {
    show() {
      this.tempGoods = null
      this.formData = null
      this.dialogVisible = true
      this.$nextTick(() => {
        this.resetForm()
      })
    },
    back() {
      this.tempGoods = null
      this.formData = null
    },
    resetForm() {
      const vm = this
      vm.$refs.form.resetFields()
      vm.reloadTableData()
    },
    search() {
      const vm = this
      vm.reloadTableData()
    },
    pageSizeChange(pageSize) {
      const vm = this

      vm.limit = pageSize

      vm.reloadTableData()
    },
    currentPageChange(page) {
      const vm = this

      vm.page = page

      vm.loadTableData()
    },
    reloadTableData() {
      const vm = this

      vm.page = 1
      vm.total = 0
      vm.BindTable = []
      vm.loadTableData()
    },
    loadTableData() {
      const vm = this

      vm.isSearch = false

      const data = {
        page: vm.page,
        limit: vm.limit
      }

      if (vm.BindForm.commodityName && vm.BindForm.commodityName.length > 0) {
        data['searchKey'] = vm.BindForm.commodityName
        vm.isSearch = true
      }

      /* if (vm.BindForm.commdityState && vm.BindForm.commdityState.length > 0) {
        data['type'] = parseInt(vm.BindForm.commdityState)
        vm.isSearch = true
      }*/

      if (vm.BindForm.goodsType && vm.BindForm.goodsType.length > 0) {
        data['type'] = vm.BindForm.goodsType
        vm.isSearch = true
      }

      if (vm.BindForm.type && vm.BindForm.type.length > 0) {
        if (vm.BindForm.type && vm.BindForm.type.length === 2) {
          data['categoryId'] = vm.BindForm.type[0]
          data['subCategoryId'] = vm.BindForm.type[1]
          vm.isSearch = true
        } else {
          data['categoryId'] = vm.BindForm.type[0]
          vm.isSearch = true
        }
      }

      vm.loading = true
      getAllCommodity(data).then(res => {
        vm.loading = false
        vm.total = res.data.data.totalRows
        vm.BindTable = res.data.data.rows ? res.data.data.rows : []
        if (this.selectList.length > 0) {
          vm.BindTable.forEach(item => {
            this.selectList.forEach(inf => {
              if (item.goodsId == inf.goodsId) {
                this.$nextTick(() => {
                  this.$refs.goodsTable.toggleRowSelection(item)
                })
              }
            })
          })
        }
      }).catch(res => {
        vm.loading = false
        if (res && res.data && res.data.errno !== 0) {
          this.$message.error(`${res.data.errmsg}（${res.data.errno}）`)
        }
      })
    },
    allSelection() {
      this.$refs.goodsTable.toggleAllSelection()
    },
    handleSelectionChange(e) {
      if (e && e.length > 0) {
        this.selectList = e
        console.log(e)
      }
    },
    setSelectList(List) {
      this.selectList = List
    },
    selectAddCommodity() {
      if (this.selectList.length > 0) {
        console.log(this.selectList)
        this.$emit('select', this.selectList)
        this.dialogVisible = false
      } else {
        return this.$message.warning('请选择添加的商品')
      }
    },
    submitForm() {
      const vm = this

      vm.$refs.skuForm.validate((valid) => {
        if (valid) {
          vm.tempGoods.selectedSku = vm.$XEUtils.clone(vm.formData.list, true)
          const skuNames = []
          vm.tempGoods.selectedSku.forEach(item => {
            skuNames.push(item.skuName + '：' + item.specName)
          })

          vm.tempGoods.goodsSkuNames = skuNames.join('；')
          console.log(vm.tempGoods)
          vm.dialogVisible = false
          vm.$emit('select', vm.tempGoods)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .def-b {
    border-left: 4px solid #3783ff;
    padding-left: 10px;
    word-break: break-all;
    width: calc(100% - 30px);
    display: flex;
    align-items: center;
  }

  .form-seach {
    padding: 20px 30px;
    padding-bottom: 0px;
    margin-bottom: 30px;
    border: 1px solid #eeeeee;

    .form-item {
      margin-bottom: 22px !important;
    }

  }

  .ele-table {
    margin-bottom: 30px;
  }
  .pagination {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  ::v-deep.el-radio {
    margin-right: 15px !important;
  }
  ::v-deep.el-radio.is-bordered+.el-radio.is-bordered {
    margin-left: 0 !important;
    margin-bottom: 15px !important;
  }
</style>
